package com.gonsin.gview.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import javax.persistence.AttributeConverter;
import java.lang.reflect.Type;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StringListConverter implements AttributeConverter<List<String>, String>, TypeHandler<List<String>> {
    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        Gson gson = new GsonBuilder()
                .enableComplexMapKeySerialization()
                .disableHtmlEscaping().create();
        if (attribute == null) {
            return null;
        }
        return gson.toJson(attribute);
    }

    @Override
    public List<String> convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return new ArrayList<>();
        }
        Gson gson = new GsonBuilder()
                .enableComplexMapKeySerialization()
                .disableHtmlEscaping().create();
        Type type = new TypeToken<List<String>>() {
        }.getType();
        return gson.fromJson(dbData, type);
    }

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, convertToDatabaseColumn(strings));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        return convertToEntityAttribute(resultSet.getString(s));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
